package handler

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"honghu_be/common"
	"honghu_be/dal"
	"honghu_be/model"
	"honghu_be/model/vo"
)

func GetAd(c *gin.Context) {
	req := &model.GetAdRequest{}
	if err := c.ShouldBindUri(req); err != nil {
		c.JSON(400, err.Error())
		return
	}
	resp, err := getAd(c, req.AdId)
	if err != nil {
		common.WriteError(c, err)
		return
	}
	c.JSON(200, resp)
}

func getAd(c *gin.Context, adId string) (*model.GetAdResponse, error) {
	pos, err := dal.GetAds(c, &dal.GetAdRequest{
		AdId: cast.ToInt(adId),
	})
	if err != nil {
		return nil, err
	}
	if len(pos) == 0 {
		return nil, errors.New(fmt.Sprintf("ad_%s not found", adId))
	}
	return &model.GetAdResponse{
		Meta: common.MetaOk,
		Ad:   vo.ToAdVo(pos[0]),
	}, nil
}
